"""Cars."""

__author__ = 'Josh Oosterman'

import random
from potv import engine
from potv import geom
from potv import input


class Car(object):
  """Base class for all cars."""
  IMAGE_PATTERN = 'vehicles/%s.png'
  SPRITES = ['green', 'hatchback', 'race_car', 'wagon']

  def __init__(self, location, type=None):
    self.location = location
    self.motion = geom.Vector()
    if type is None:
      type = random.choice(self.SPRITES)
    self.image = engine.LoadImage(self.IMAGE_PATTERN % type)
    self.image.CenterOrigin()

  def Step(self):
    direction, speed = self.motion.ToAngleMagnitude()
    steering_speed = 3.0
    acceleration = 0.8
    braking = 0.2
    if input.IsDown(input.CAR_ACCELERATE):
      speed += acceleration
    if input.IsDown(input.CAR_DECELERATE):
      speed -= braking
    if input.IsDown(input.CAR_STEER_LEFT):
      direction += steering_speed
    if input.IsDown(input.CAR_STEER_RIGHT):
      direction -= steering_speed
    speed = max(0.0, min(15.0, speed))
    self.motion.FromAngleMagnitude(direction, speed)
    self.location += self.motion

  def Draw(self, view):
    angle, _ = self.motion.ToAngleMagnitude()
    rotated = self.image.Rotated(angle)
    view.DrawImage(rotated, self.location)

